package ar.com.spsolutions.splibrary.services;

import org.joda.time.DateTime;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;

import ar.com.spsolutions.splibrary.book.LoanBook;
import ar.com.spsolutions.splibrary.general.RoleConverterService;

public class LoanBookService extends TemplateEntityService<LoanBook> {

	private static final long serialVersionUID = 6980902021638618675L;

	@Transactional(readOnly = true)
	public DateTime getExpirationDate(final LoanBook loan) {
		return loan.getExpirationDate();
	}

	@Override
	@Secured(value = { RoleConverterService.ROLE_USER })
	public LoanBook get(final LoanBook loan) {
		final LoanBook result = this.getRepository().findById(loan.getId());
		result.setNotifier(this.getNotifier());
		return result;
	}

	@Transactional(readOnly = true)
	public void notifyDues() {
		for (final LoanBook loanBook : this.findAll()) {
			if (loanBook.isDue() && !loanBook.isNotified()) {
				loanBook.setNotifier(this.getNotifier());
				loanBook.notifyBookDue();
			}
		}
	}

	@Override
	@Secured(value = { RoleConverterService.ROLE_USER })
	public void add(final LoanBook aEntity) {
		super.add(aEntity);
	}
}
